package com.gurumades.jsonform.client.forms;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.Widget;
import com.gurumades.jsonform.client.JSONUtils;

public class FormItemViewCheckBox extends FormItemViewAbstract {

	private static final Binder binder = GWT.create(Binder.class);

	interface Binder extends UiBinder<Widget, FormItemViewCheckBox> {
	}

	protected PushButton toggleButton;
	
	protected String widget;
	
	public FormItemViewCheckBox() {
		initWidget(binder.createAndBindUi(this));
	}

	
	
	@Override
	public void setData(JSONValue object) {
		if (object.isObject() != null) {
			object = object.isObject().get("value");
			setValue(object.isBoolean().booleanValue());
		}
	}
	
	private void setValue(boolean value) {
		if (widget.endsWith("toggle")) {
			toggleButton.setTitle("PushButton");
		}else{
			((CheckBox) this.value).setValue(value);
		}
		
	}

	@Override
	public boolean isValueEmpty() {
		return false;
	}

	@Override
	public JSONObject getValue() {
		CheckBox box = (CheckBox) this.value;
		JSONObject object = new JSONObject();
		object.put("value", JSONBoolean.getInstance(box.getValue()));
		return object;
	}

	@Override
	public void initFormItem(JSONValue value, JSONObject formItemSettings) {
		String type = JSONUtils.getString("type", formItemSettings);

		this.widget = type;
		
		if (type.endsWith("toggle")) {
			Widget wgt = this.value;
			Element parentElement = wgt.getParent().getElement();
			
			toggleButton = new PushButton();
			toggleButton.setSize("30px", "30px");
			
			parentElement.appendChild(toggleButton.getElement());
			wgt.removeFromParent(); 
		} else {
			((CheckBox) this.value).setText(JSONUtils.getString("label",
					formItemSettings));
			formItemSettings.put("label", null);
			super.initFormItem(value, formItemSettings);
		}
	}

}
